﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using OTE.Contract;
using OTE.Tasks.Commands.Test;
using OTE.Web.Infrastructure;
using OTE.Web.Infrastructure.Utils;
using OTE.Web.Mvc.Queries.Test;
using OTE.Web.Mvc.ViewModels.Test;

namespace OTE.Web.Mvc.Controllers
{
    public class TestController : OTEController
    {
        public ITestQuery TestQuery { get; private set; }

        public TestController(ITestQuery testQuery)
        {
            TestQuery = testQuery;
        }

        public ActionResult Index()
        {
            string username = User != null ? User.Identity.Name : "";
            //create random question
            if (WebSession[Constants.RESULT_LIST] == null)
            {
                WebSession[Constants.RESULT_LIST] = new Dictionary<int, int>();
                var lstQuestions = TestQuery.CreateQuestionForTest(10, 1, 2, username);

                //add random questions into tmp table
                foreach (QuestionDTO q in lstQuestions)
                {
                    TestMetaDataAddedCommand command = new TestMetaDataAddedCommand()
                    {
                        CreatedBy = username,
                        QuestionId = q.Id,
                        QuestionTypeId = q.QuestionTypeId,
                        UserId = 2,
                        Content = q.Content
                    };
                    var result = CommandProcessor.Process(command);
                }
            }

            //get question
            var questions = GetQuestion(1, 5, 2);

            var viewModel = new TestListViewModel() { Questions = questions, PageIndex = 1, StartTime = DateTime.Now, TestTime = 10 };

            viewModel.TimeLeft = (long)viewModel.StartTime.AddMinutes(viewModel.TestTime).Subtract(DateTime.Now).TotalSeconds;

            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Index(TestListViewModel viewModel)
        {
            //validate the time is empty then save result to db
            if (DateTime.Now.Subtract(viewModel.StartTime).TotalMinutes >= viewModel.TestTime)
                return Index();

            if (!string.IsNullOrEmpty(viewModel.SelectedAnswer) && !string.IsNullOrEmpty(viewModel.SelectedQuestion))
            {
                //if (WebSession[Constants.RESULT_LIST] == null)
                //    WebSession[Constants.RESULT_LIST] = new Dictionary<int, int>();

                var tmpResult = (Dictionary<int, int>)WebSession[Constants.RESULT_LIST];

                //get question id
                string[] arrQuestions = viewModel.SelectedQuestion.Split('|');

                //get answer id
                string[] arrAnswers = viewModel.SelectedAnswer.Split('|');

                for (var i = 0; i < arrQuestions.Length - 1; i++)
                {
                    var questionId = Convert.ToInt32(arrQuestions[i]);
                    var answerId = Convert.ToInt32(arrAnswers[i]);
                    //validate that the key of question has not existed then add into result list
                    if (!tmpResult.ContainsKey(questionId))
                        tmpResult.Add(questionId, answerId);
                    //else if existed then update answer id
                    else
                    {
                        tmpResult[questionId] = answerId;
                    }
                }

                //set resutl to session
                WebSession[Constants.RESULT_LIST] = tmpResult;
            }

            var questions = GetQuestion(viewModel.PageIndex, 5, 2);

            var vm = new TestListViewModel() { Questions = questions, PageIndex = viewModel.PageIndex, StartTime = viewModel.StartTime, TestTime = viewModel.TestTime };

            vm.TimeLeft = (long)vm.StartTime.AddMinutes(vm.TestTime).Subtract(DateTime.Now).TotalSeconds;

            return View(vm);
        }

        private List<TestItemViewModel> GetQuestion(int pageIndex, int pageSize, int userId)
        {
            var totalPage = 0;
            var questions = TestQuery.GetQuestion(pageIndex, pageSize, userId, ref totalPage);

            ViewData[Constants.PAGE_INDEX] = pageIndex;

            ViewData[Constants.TOTAL_PAGE] = totalPage;

            Dictionary<int, int> tmpResult = null;
            //if (WebSession[Constants.RESULT_LIST] != null)
            tmpResult = (Dictionary<int, int>)WebSession[Constants.RESULT_LIST];
            //else
            //    tmpResult = new Dictionary<int, int>();

            for (var i = 0; i < questions.Count; i++)
            {
                //get result from memory if existed
                if (tmpResult.ContainsKey(questions[i].Id))
                    questions[i].SelectedAnswer = tmpResult[questions[i].Id];
                else
                    questions[i].SelectedAnswer = 0;
            }

            return questions;
        }
    }
}